package threads.collaboration;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class StringProcessingThread implements Callable<ResultWrapper>
{
	
	private final CountDownLatch latch;
	private String source;
	private int partNumber;
	
	public StringProcessingThread(CountDownLatch latch, String source, int partNumber)
	{
		this.latch = latch;
		this.source = source;
		this.partNumber = partNumber;
	}
	

	public ResultWrapper call()
	{
		//doSmth(source);
		
//		try
//		{
//			TimeUnit.MILLISECONDS.wait(100);
//		}
//		catch (InterruptedException e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		long start = System.currentTimeMillis();
		ResultWrapper rw = new ResultWrapper();
		rw.setNumber(partNumber);
		rw.setResultString(reverse(source));
		long finish = System.currentTimeMillis();
		System.out.println("Thread " + Thread.currentThread() + ": finished job for " + (finish-start) + " ms");
		latch.countDown();
		return rw;
	}
	
	private void doSmth(String str)
	{
		System.out.println("Thread " + Thread.currentThread() + ": finished job with " + str + ";" + latch.getCount()); 
		
	}
	
	private String reverse(String input) {
		
		char[] array = input.toCharArray();
		
		for (int index = 0; index < array.length/2; index++) {
			
			//System.out.println("index = " + index);
			char tempFromStart = array[index];
			//System.out.println("tempFromStart = " + tempFromStart);
			
			char tempFromEnd = array[array.length - 1 - index];
			//System.out.println("tempFromEnd = " + tempFromEnd);
			
			array[index] = tempFromEnd;
			array[array.length - 1 - index] = tempFromStart;
			
			//System.out.println(array);
			//System.out.println("======================");
		}
		
		return new String(array);
	} 
	
	
}
